package com.hd.sup.modules.enterprise.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hd.common.constant.BizConstant;
import com.hd.common.utils.CollectionUtils;
import com.hd.common.utils.GenUtil;
import com.hd.common.utils.ValueUtils;
import com.hd.sup.config.redis.prefix.CacheKey;
import com.hd.sup.config.redis.utils.JedisUtil;
import com.hd.sup.core.rest.client.AuthRestClient;
import com.hd.sup.core.rest.dto.TData;
import com.hd.sup.modules.district.model.Region;
import com.hd.sup.modules.district.service.IRegionService;
import com.hd.sup.modules.enterprise.mapper.EnterpriseMapper;
import com.hd.sup.modules.enterprise.model.Enterprise;
import com.hd.sup.modules.enterprise.service.IEnterpriseService;
import com.hd.sup.modules.vehicle.service.IVehicleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chentl123
 * @since 2020-12-28
 */
@Slf4j
@Service
public class EnterpriseServiceImpl extends ServiceImpl<EnterpriseMapper, Enterprise> implements IEnterpriseService {

    @Resource
    private AuthRestClient authRestClient;

    @Resource
    private JedisUtil jedisUtil;

    @Resource
    private IRegionService regionService;

    @Resource
    private IVehicleService vehicleService;

    @Override
    public List<Map<String, Object>> pageList(Page page, Enterprise enterprise) {
        return this.baseMapper.pageList(page, enterprise);
    }

    @Override
    public Integer countEnterpriseNum(String regionCode, List<String> deptIds) {
        return this.baseMapper.countEnterpriseNum(regionCode, deptIds);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void generateEnterprise(TData data) {
        String enterpriseNo = data.getId_owner();
        String enterpriseName = data.getOwnername();
        String industry = data.getMgrarea();
        String region = data.getOrigziparea();
        String contactor = data.getContactor();
        String contactorPhone = data.getTel();
        String issueOffice = data.getGrantorgan();
        String address = data.getAddress();

        //入库企业
        int e_db = this.baseMapper.selectCount(new LambdaQueryWrapper<Enterprise>().eq(Enterprise::getEnterpriseNo, enterpriseNo));
        if (e_db == 0) {
            // 调用权限接口 插入组织机构企业信息 获取返回的 deptId 插入企业数据
            Region regionDb = regionService.getOne(new LambdaQueryWrapper<Region>().eq(Region::getCode, region));
            if (regionDb == null) {
                log.error("[supervise] 行政编码: {} 对应的 regionDb 不存在", region);
                return;
            }

            String parentId = regionDb.getDeptId();
            Enterprise ep = new Enterprise(enterpriseNo, enterpriseName, industry, region, contactor, contactorPhone, issueOffice, address, parentId);
            String res = authRestClient.saveEnterpriseToAuth(ep);
            if (StringUtils.isEmpty(res)) {
                log.error("[supervise] 权限系统企业数据插入失败，返回结果为空");
                return;
            }
            JSONObject apiData = (JSONObject) JSONObject.parse(res);
            JSONObject result = (JSONObject) apiData.get("result");
            String deptId = (String) result.get("deptId");
            if (StringUtils.isBlank(deptId)) return;

            ep.setDeptId(deptId);
            ep.insert();
            log.info("[schedule] 企业静态信息已入库,企业编号:{} 企业名称:{}", enterpriseNo, enterpriseName);

            //缓存企业静态信息
            jedisUtil.hset(CacheKey.STATIC_DATA_ENTERPRISE, enterpriseNo, JSON.toJSONString(ep));
            log.info("[schedule] 企业静态信息缓存已刷新,企业编号:{} 企业名称:{}", enterpriseNo, enterpriseName);
        }
    }

    @Override
    public List<Map<String, Object>> selectAllMaps() {
        return this.baseMapper.selectAllMaps();
    }

    @Async("superviseTaskExecutor")
    @Override
    public void cacheStaticData() {
        // 启动时加载所有 车辆静态信息 和 企业静态信息到缓存中，
        Map<String, List<Map<String, Object>>> all = Maps.newHashMap();
        List<Map<String, Object>> vehicleList = Lists.newArrayList();
        List<Map<String, Object>> enterpriseList = Lists.newArrayList();
        List<Map<String, Object>> vDb = vehicleService.selectAllMaps();
        List<Map<String, Object>> eDb = selectAllMaps();

        if (CollectionUtils.isNotEmpty(vDb)) {
            for (Map<String, Object> one : vDb) {
                String plat_no = ValueUtils.parseString(one.get("platNo"));
                String plat_no_color = ValueUtils.parseString(one.get("platNoColor"));
                Map<String, Object> vMap = Maps.newHashMap();
                vMap.put(BizConstant.Common.FIELD.key(), GenUtil.cacheKey(plat_no, BizConstant.Common.UNDERLINE.key(), plat_no_color));
                vMap.put(BizConstant.Common.VAL.key(), JSON.toJSON(one));
                vehicleList.add(vMap);
            }
        }

        if (CollectionUtils.isNotEmpty(eDb)) {
            for (Map<String, Object> one : eDb) {
                String enterprise_no = ValueUtils.parseString(one.get("enterpriseNo"));
                Map<String, Object> vMap = Maps.newHashMap();
                vMap.put(BizConstant.Common.FIELD.key(), GenUtil.cacheKey(enterprise_no));
                vMap.put(BizConstant.Common.VAL.key(), JSON.toJSON(one));
                enterpriseList.add(vMap);
            }
        }
        all.put(CacheKey.STATIC_DATA_VEHICLE, vehicleList);
        all.put(CacheKey.STATIC_DATA_ENTERPRISE, enterpriseList);

        //缓存
        jedisUtil.hsetbatch(all);
        log.info("[redis] 车辆、企业静态信息已缓存");
    }

    @Override
    public void deleteByIds(List<String> ids) {
        removeByIds(ids);

        //清理缓存
        List<Enterprise> enterprises = listByIds(ids);
        String[] es = enterprises.stream().map(Enterprise::getEnterpriseNo).toArray(String[]::new);

        jedisUtil.hdel(CacheKey.STATIC_DATA_ENTERPRISE, es);
        log.info("[redis] 企业缓存已对应删除");

    }
}
